<template>
  <card-group-solt
    @handleClick="changeTab"
    :activeName="activeName"
    :tabPanes="tabPanes"
    :cardLoading="activeName === 'cdr_call' || activeName === 'cdr_outbound' ? false : loading"
  >
    <template :slot="'search'">
      <search
        :type="activeName"
        v-show="this.$route.path.split('/')[2]==='call' && activeName !== 'cdr_call' && activeName !== 'cdr_outbound'"
      >
        <template :slot="'select'">
          <v-select
            :selectOptions="search[activeName].isChildren.quickSelect"
            :form="search[activeName].isChildren.nomalForm"
            @quickSelect="quickSelect"
            :isCall="true"
          ></v-select>
        </template>
        <template :slot="'inputSearch'">
          <input-search
            :placeHolder="$t('call.enterCallnumOrCallednumForQuery')"
            :form="search[activeName].isChildren.nomalForm"
            @quickSearch="inputSearch"
          ></input-search>
        </template>
        <template :slot="'advancedSearch'">
          <advanced-search
            :adv="search[activeName].isChildren.adv"
            :isClear="isClear"
            :callServerNo="callServerNo"
            :isCall="true"
            :activeName="activeName"
            :callTimeLimit="getSessionCallTimeLimit"
            :formItemsConfig="formItemsConfigs && formItemsConfigs[activeName]"
            @restForm="restForm"
            @advSearch="advSearch"
            @selectChange="handlerSelectChange"
            @confirmNewItemsConfig="handleConfirmNewItemsConfig"
          ></advanced-search>
        </template>
        <template :slot="'advSchBadge'">
          <advSchBadge
            :badge="search[activeName].isChildren.adv.badgeList"
            @removeBadge="removeBadge"
          ></advSchBadge>
        </template>
        <template :slot="'refresh'">
          <refresh @refresh="handleRefresh" :class="'positionClass'"></refresh>
        </template>
        <template :slot="'leakSheet'">
          <span v-show="activeName ==='cdr_all'">
            <dropdown-menu
              :newEmptySeat="newEmptySeat"
              :isCallLeakSheet="isCallLeakSheet"
              :isCallExport="isCallExport"
              :tabType="'call'"
            ></dropdown-menu>
          </span>
        </template>
      </search>
    </template>
    <template :slot="'cardList'">
      <call-card
        :callCardList="cardList"
        :qu="qu"
        :allCount="allCount"
        :type="type"
        :tabType="activeName"
        :clearChecked="clearChecked"
        @changeProccessStatus="changeProccessStatus"
        :condition="search[activeName].isChildren.adv.condition"
      ></call-card>
    </template>
    <template slot="pagination">
      <pagination
        :moreFlag="moreFlag"
        :customerShow="true"
        :small="true"
        :currentPage="currentPage"
        :count="count"
        :allCount="allCount"
        :type="type"
        :tabType="activeName"
        @turnPage="turnPage"
        :totalPage="totalPage"
        @getAllCount="getAllCount"
      ></pagination>
    </template>
  </card-group-solt>
</template>
<script>
  // 此组件是通话左侧，包括卡片，高级搜索，普通搜索，快捷搜索，更多操作（未接来电管理 && 批量下载录音任务管理）
  // 1、去掉已处理tab页，仅支持座席在全部tab页中查看已处理过的和未接的通话记录。2018/08/06
  // 2、待处理只保留分配给座席的未接来电 2018/08/06
  import CardGroupSolt from '@/components/public-modules/card/NewIndex.vue'
  import DropdownMenu from '@/components/public-modules/card/search/DropdownMenu.vue'
  import CallCard from './CallCard'
  import Search from '@/components/public-modules/card/search/NewIndex.vue'
  import Select from '@/components/public-modules/card/search/Select'
  import InputSearch from '@/components/public-modules/card/search/InputSearch'
  import AdvancedSearch from '@/components/public-modules/card/search/Advanced1Search.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import Refresh from '../../ui-modules/icon/Refresh'
  import {getFormatDateTime, deepClone, isHasMenu, isHasFunc, m7Language} from '@/utils/m7Utils'
  import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge'
  import { changeActiveTab, changeActiveList } from '@/utils/shortcutKey'
  import {getAllUseMultiCallLabel} from '@/utils/m7Utils.js'
import leadInTemplateVue from '../config/agentConfig/info/SearchAgentListBase/leadInTemplate.vue'
  // import customerApi from '@/store/api/customer'
export default {
  name: 'CallCardGroup',
  watch: {
    $route(to, from) {
      const routeArr = to.path.split('/')
      try {
        if (to.meta.title !== from.meta.title) {
          const title = to.meta.title
          if ( title === 'callBlank' || title === 'call') {
            document.addEventListener('keydown', this.shortcutDispatch)
          } else {
            document.removeEventListener('keydown', this.shortcutDispatch)
          }
        }
      } catch(err) {
        console.log(err)
      }
      if (routeArr[2] === 'call') {
        this.invokMethod(to, from)
        if (routeArr.length <= 4) {
          this.$store.commit('BLANK', routeArr[3])
        }
      }
    },
    cardList (data) {
      if (this.activeName === 'cdr_call' && data.length === 1) { // 只有一个list的时候自动弹开右侧
        this.pushFirstUrl()
      }
    },
    shortcutOpen () {
      if(this.shortcutOpen) {
        document.addEventListener('keydown', this.shortcutDispatch)
      } else {
        document.removeEventListener('keydown', this.shortcutDispatch)
      }
    }
  },
  data() {
    return {
      pages: 0,
      callServerNo: [],
      allCount: 0,
      qu: {},
      loading: true,
      activeName: 'cdr_call',
      type: 'call',
      clearChecked: '',
      newEmptySeat: false,
      temporaryCom: '',
      transferBeforeSeatCom: '',
      transferBeforeSeatDep: '',
      transferBeforeSeat: '',
      multiTempCom: [],
      custType: '',
      temporaryDep: '',
      temporaryAgent: '',
      search: {
        isAdvSearch: false,
        isSearch: false,
        cdr_call: {
          show: false,
          pagination: {
            small: true,
            currentPage: 1
          },
          isChildren: {
            rel: false,
            select: true,
            nomal: true,
            nomalForm: {query: '', flow: '', value: ''},
            adv: {
              form: {},
              advSearchOptions: {
                localed: [],
                custom: []
              },
              badgeList: {},
              condition: {}
            },
            quickSelect: [],
            inputSearch: {
              phoneNum: ''
            },
          }
        },
        cdr_pending: {
          show: true,
          pagination: {
            small: true,
            currentPage: 1,
          },
          isChildren: {
            rel: false,
            select: true,
            nomal: true,
            nomalForm: { query: '', flow: 'week', value: 'week' },
            quickSelect: [
              { label: this.$t('webchat.today'), value: 'today' },
              { label: this.$t('webchat.yesterday'), value: 'yesterday' },
              { label: this.$t('webchat.lastWeek'), value: 'week' },
              { label: this.$t('webchat.lastMonth'), value: 'month' }
            ],
            inputSearch: {
              phoneNum: ''
            },
            refresh: true,
            adv: {
              form: {
                QUICK_QUERY_NUM: '',
                CALL_NO: '',
                CALLED_NO: '',
                CALLBACK_AGENT: '',
                ownercom: '',
                DISPOSAL_AGENT: '',
                ownerdep: '',
                ownercomRefDisposalAgent: '',
                REF_DISPOSAL_AGENT: '',
                ownerdepRefDisposalAgent: '',
                STATUS: '',
                ERROR_MEMO: [],
                INVESTIGATE: [],
                appraise: [],
                CUSTOMER_NAME: '',
                CALL_TIME_LENGTH_BEGIN: '',
                CALL_TIME_LENGTH_END: '',
                RING_TIME_LENGTH_BEGIN: '', // 振铃时长
                RING_TIME_LENGTH_END: '',
                QUEUE_TIME_LENGTH_BEGIN: '',
                QUEUE_TIME_LENGTH_END: '',
                KEY_TAG: '',
                QUICK_HANGUP: '',
                CALL_LABEL: [],
                multiLabel: [],
                multiCallLabels: [],
                SQ_LABEL: '',
                OFFERING_TIME: null,
                HANGUP_TIME: null,
                REPEAT_CALL: [],
                CONNECT_TYPE: '',
                IS_BUSINESS_ASSOCIATED: '',
                CALL_MEMO: ''
              },
              advSearchOptions: {
                localed: [],
                custom: []
              },
              badgeList: {},
              condition: {}
            }
          }
        },
        cdr_all: {
          show: true,
          pagination: {
            small: true,
            currentPage: 1,
          },
          isChildren: {
            rel: true,
            select: true,
            nomal: true,
            nomalForm: { query: '', flow: 'week', value: 'week' },
            quickSelect: [
              { label: this.$t('webchat.today'), value: 'today' },
              { label: this.$t('webchat.yesterday'), value: 'yesterday' },
              { label: this.$t('webchat.lastWeek'), value: 'week' },
              { label: this.$t('webchat.lastMonth'), value: 'month' },
              { label: this.$t('call.myCdrCall'), value: 'mycall' }
            ],
            inputSearch: {
              phoneNum: ''
            },
            refresh: true,
            adv: {
              form: {
                QUICK_QUERY_NUM: '',
                CALL_NO: '',
                CALLED_NO: '',
                ownercom: '',
                DISPOSAL_AGENT: '',
                ownerdep: '',
                ownercomRefDisposalAgent: '',
                REF_DISPOSAL_AGENT: '',
                ownerdepRefDisposalAgent: '',
                STATUS: '',
                ERROR_MEMO: [],
                INVESTIGATE: [],
                appraise: [],
                CUSTOMER_NAME: '',
                CALL_TIME_LENGTH_BEGIN: '',
                CALL_TIME_LENGTH_END: '',
                RING_TIME_LENGTH_BEGIN: '', // 振铃时长
                RING_TIME_LENGTH_END: '',
                QUEUE_TIME_LENGTH_BEGIN: '',
                QUEUE_TIME_LENGTH_END: '',
                KEY_TAG: '',
                QUICK_HANGUP: '',
                CALL_LABEL: [],
                multiLabel: [],
                multiCallLabels: [],
                SQ_LABEL: '',
                OFFERING_TIME: null,
                HANGUP_TIME: null,
                isPermissions: '',
                REPEAT_CALL: [],
                CONNECT_TYPE: '',
                IS_BUSINESS_ASSOCIATED: '',
                CALL_MEMO: ''
              },
              advSearchOptions: {
                localed: [],
                custom: []
              },
              badgeList: {},
              condition: {}
            }
          }
        },
        cdr_outbound: {
          show: false,
          pagination: {
            small: true,
            currentPage: 1,
          },
          isChildren: {
            rel: false,
            select: true,
            nomal: true,
            nomalForm: { query: '', flow: '', value: '' },
            adv: {
              form: {},
              advSearchOptions: {
                localed: [],
                custom: [],
              },
              badgeList: {},
              condition: {},
            },
            quickSelect: [],
            inputSearch: {
              phoneNum: ''
            }
          }
        }
      },
      card: {
        cdr_call: {
          count: ''
        },
        cdr_outbound: {
          count: ''
        },
        cdr_pending: {
          count: ''
        },
        cdr_all: {
          count: ''
        }
      },
      isClear: false,
      formItemsConfigs: {}
    }
  },
  components: {
    CallCard,
    Search,
    "v-select": Select,
    CardGroupSolt,
    InputSearch,
    AdvancedSearch,
    Pagination,
    Refresh,
    AdvSchBadge,
    DropdownMenu
  },
  methods: {
    shortcutDispatch(e) {
      if (e.altKey && e.keyCode === 39) { //right
        changeActiveTab({
          el: this.$el,
          isIncrease: true,
        })
      }
      if (e.altKey && e.keyCode === 37) { //left
        changeActiveTab({
          el: this.$el,
        })
      }
      const list = {
        boxClass: 'el-menu',
        activeClass: 'is-active',
        itemClass: 'el-menu-item'
      }
      if (this.cardList.length === 0) {
        return
      }
      if (e.altKey && e.keyCode === 40) { // down
        changeActiveList({
          list,
          el: this.$el,
          isIncrease: true
        })
        // this.changeActiveChannel(list, true)
      }
      if (e.altKey && e.keyCode === 38) { // up
        changeActiveList({
          list,
          el: this.$el
        })
        // this.changeActiveChannel(list)
      }
    },
    invokMethod(to, from) { // 来电&&智能质检&&分配未接来电跳转
      if (
        this.$route.query &&
        this.$route.query.status &&
        this.$route.query.status === 'autoqc'
      ) {
        this.routeToMe(to, from)
      } else if (
        this.$route.query &&
        this.$route.query.pending &&
        this.$route.query.pending === 'leakAssignMsg'
      ) {
        // 分配未接来电点击路由跳转后查询查询一次待处理
        this.isChangePendingData(to, from)
      } else if (
        from &&
        from.path.indexOf('cdr_') > -1 &&
        to.query.flag === 'notify'
      ) {
        // 当前在通话模块，点击浏览器提醒
        this.activeName = to.path.split('/')[3]
      }
    },
    isChangePendingData(to, from) {
      // 点击分配未接来电跳转
      this.loading = true
      this.clearSearchQuery()
      this.search.cdr_pending.isChildren.adv.badgeList = {}
      this.search.cdr_pending.pagination.currentPage = 1
      this.search.cdr_pending.isChildren.nomalForm = {
        query: '',
        flow: '',
        value: ''
      }
      this.getCallList(this.$store, 1, 'cdr_pending', 1).then(() => {
        this.loading = false
        if (from && from.path.indexOf('cdr_') > -1) {
          // 当前在通话模块，跳转进来
          this.activeName = 'cdr_pending'
          this.$store.commit('BLANK', 'cdr_pending')
        }
      })
    },
    routeToMe(to, from) {
      // 点击质检提醒跳转通话
      let query = this.$route.query
      if (query && query.active && query.callId) {
        let form = {
          CALL_SHEET_ID: query.callId,
          page: 1,
          pageSize: 10,
          morePage: 1,
          autoqc: true,
          type: 'cdr_all'
        }
        if (
          query.active === 'cdr_all' &&
          this.$store.state.session.user.isAdmin &&
          isHasFunc(
            'func_not_allow_public_record',
            this.$store.state.session.user
          )
        ) {
          form.isPermissions = false
        }
        this.$store.dispatch('queryCallList', form).then((res) => {
          this.loading = false
          if (res && res.list.length) {
            this.$router.push(
              '/index/call/' +
                query.active +
                '/' +
                query.callId +
                '/?random=' +
                Math.random()
            )
            this.$store.commit('call/REFRESH_CUST_RIGHT', Math.random())
          } else {
            this.$router.push('/index/call/' + query.active)
          }
          if (from && from.path.indexOf('cdr_') > -1) {
            // 当前在通话模块，跳转进来
            this.activeName = query.active
          }
        })
      }
    },
    pushFirstUrl() {
      let list = this.$store.state.call.callList.cdr_call.list || []
      const routeArr = this.$route.path.split('/')
      if (
        routeArr[3] === 'cdr_call' &&
        list.length === 1 &&
        routeArr[2] === 'call'
      ) {
        // 是来电模块 && list的长度是1
        let callId = list[0].CALL_SHEET_ID
        if (callId) {
          setTimeout(() => {
            // 当前在来电页面，只有一个来电，并且开启了来电自动保存客户的时候，因为异步问题会导致右侧组件加载错误，此方法影响范围最小，否则改动太大，影响范围大。
            this.$router.push({
              path: '/index/call/cdr_call/' + callId + '/cdr?flag=list',
            })
          }, 500)
        }
      }
    },
    // 查看更多记录
    getAllCount() {
      this.allCount = 0
      let form = this.qu
      form.queryCount = true
      form.searchAllCount = true // 此参数是防止vuex的值被改动
      let activeName = this.activeName
      let page = this.search[activeName].pagination.currentPage || 1
      let more = false
      let isGetAllCount = true
      this.getCallList(
        this.$store,
        1,
        this.activeName,
        page,
        form,
        isGetAllCount
      ).then((resp) => {
        delete this.qu.searchAllCount
        if (resp && resp.success) {
          this.allCount = resp.count
          this.$store.commit('call/SET_CALL_MORE', { activeName, more })
          this.loading = false
        }
      })
    },
    getLastParameter(parameter) {
      let parameterObj = null
      if (parameter) {
        if (Array.isArray(parameter) && parameter.length === 2) {
          if (parameter[0] && parameter[1]) {
            // condition.OFFERING_TIME = {} 的时候，后台查询没有数据
            parameterObj = {}
            if (parameter[0] instanceof Date) {
              parameterObj.$gte = getFormatDateTime(parameter[0])
            }
            if (parameter[1] instanceof Date) {
              parameterObj.$lte = getFormatDateTime(parameter[1])
            }
          } else {
            parameterObj = null
          }
        } else {
          parameterObj = null
        }
      }
      return parameterObj
    },
    getCallList(
      store,
      morePage,
      tabName,
      pageNum,
      queryCondition,
      isGetAllCount
    ) {
      if (!queryCondition) {
        queryCondition = {}
      }
      let condition = deepClone(queryCondition)
      let offerTime = queryCondition.OFFERING_TIME
      let endTime = queryCondition.HANGUP_TIME
      if (!isGetAllCount) {
        // 解决查看总数时，参数被整改的问题
        if (offerTime && typeof offerTime[0] === 'string') {
          condition.OFFERING_TIME = { $gte: offerTime[0], $lte: offerTime[1] }
        } else {
          condition.OFFERING_TIME = this.getLastParameter(offerTime)
        }
        condition.HANGUP_TIME = this.getLastParameter(endTime)
      }
      condition.page = pageNum || 1
      condition.pageSize = 10
      condition.type = tabName
      condition.morePage = morePage || 1
      let userId = store.state.session.user._id
      if (tabName === 'cdr_pending') {
        condition.DISPOSAL_AGENT = userId
        condition.tabName = tabName
      }
      if (
        tabName === 'cdr_all' &&
        !store.state.session.user.isAdmin &&
        isHasFunc('func_not_allow_public_record', store.state.session.user)
      ) {
        condition.isPermissions = false
      } else {
        delete condition.isPermissions
      }
      let custom = queryCondition.custom
      for (let key in custom) {
        condition[key] = custom[key]
      }
      delete condition.custom
      for(let key in condition){
        if(key=='CALL_LABEL'||key=='multiCallLabels'){
          delete condition[key]
        }
      }
      if(condition.multiLabel&&condition.multiLabel.length>0&&condition.multiLabel[0]!=='noLabel'){
        condition.callFlag=true
      }
      if (condition.ownercom && condition.ownercom.indexOf('__') > -1) {
        condition.ownercom = condition.ownercom.substr(
          0,
          condition.ownercom.indexOf('__')
        )
      }
      let _qu = deepClone(condition)
      delete _qu.INVESTIGATE
      _qu.queryCount = true
      this.qu = _qu
      let _form = deepClone(condition)
      if (_form.CUSTOMER_NAME && _form.CUSTOMER_NAME === 'Unknown customer') {
        _form.CUSTOMER_NAME = '未知客户'
      } else if (
        _form.CUSTOMER_NAME &&
        _form.CUSTOMER_NAME === 'Multiple matching customers'
      ) {
        _form.CUSTOMER_NAME = '多个匹配客户'
      }
      delete _form.INVESTIGATE
      if (tabName === 'cdr_pending') {
        let userId = this.$store.state.session.user._id
        let queryData = {}
        if (condition.OFFERING_TIME) {
          queryData = {
            CALLBACK_AGENT: userId,
            OFFERING_TIME: condition.OFFERING_TIME,
          }
        } else {
          queryData = { CALLBACK_AGENT: userId }
        }
        store.dispatch('getPendingCallSheetCount', queryData)
        return store
          .dispatch('queryPendingCallSheet', condition)
          .then((resp) => {
            if (condition.page === 1) {
              this.pages = this.count / 10
            }
            return resp
          })
      } else {
        return store.dispatch('queryCallList', _form).then((resp) => {
          if (condition.page === 1) {
            this.pages = this.count / 10
          }
          return resp
        })
      }
    },
    changeProccessStatus(data, tabType) {
      // 把未处理的通话标记成已处理
      if (tabType === 'cdr_call') {
        // 来电列表
        this.$store.commit('call/DELETE_CURRENT_CDR_CALL', {
          _id: data._id,
          tabType: 'cdr_call',
        })
        this.$store.commit('call/SET_READ', data._id) // 先设置成已读
        this.$store.commit('call/COUNT_UNREAD_CDR') // 再次计算未读数

        // ADD by liangqi
        this.$store.commit('REMOVE_ROUTE', {
          type: 'call',
          id: data._id,
        })
        // ADD end
        if (data._id === this.$route.path.split('/')[4]) {
          // 删除的id是当前操作的卡片才重新push路由
          this.$router.push({
            path: '/index/call/' + tabType + '?flag=delete',
          })
        }
      } else if (tabType === 'cdr_outbound') {
        // 外呼去电
        this.$store.commit('call/DELETE_CURRENT_CDR_CALL', {
          _id: data._id,
          tabType: 'cdr_outbound',
        })
        if (data._id === this.$route.path.split('/')[4]) {
          // 删除的id是当前操作的卡片才重新push路由
          this.$router.push({
            path: '/index/call/' + tabType + '?flag=delete',
          })
        }
      } else {
        this.$store
          .dispatch('changeCallSheetProccessStatus', data)
          .then((resp) => {
            if (resp && resp.success) {
              // 重新请求
              this.search.isSearch = true
              let form = this.search[this.activeName].isChildren.adv.form
              this.getCallList(this.$store, 1, this.activeName, 1, form).then(
                () => {
                  this.loading = false
                  this.allCount = 0
                }
              )
            }
          })
      }
    },
    // 重置表单
    clearSearchQuery() {
      let currentTab = this.search[this.activeName]
      for (let key in currentTab.isChildren.adv.form) {
        if (key === 'REPEAT_CALL' || key === 'ERROR_MEMO') {
          currentTab.isChildren.adv.form[key] = []
        } else if (key !== 'custom') {
          // 重置弹框表单
          currentTab.isChildren.adv.form[key] = null
        } else {
          currentTab.isChildren.adv.form[key] = {}
        }
      }
      for (let key in this.search[this.activeName].isChildren.nomalForm) {
        // 重置快捷表单
        this.search[this.activeName].isChildren.nomalForm[key] = null
      }
    },
    setQuickSeachTitle(value) {
      if (this.search[this.activeName].isChildren.nomalForm) {
        this.search[this.activeName].isChildren.nomalForm.flow = value
        this.search[this.activeName].isChildren.nomalForm.value = value
      }
    },
    pushCdrCallRoute(url) {
      this.$router.push({ path: url })
    },
    changeTab(tabName) {
      // console.log(tabName)
      // tab切换
      this.allCount = 0
      this.pages = 0
      this.activeName = tabName
      this.$store.commit('BLANK', tabName)
      this.search.isSearch = true
      this.$emit('tabChange', tabName)
      this.loading = true
      this.clearSearchQuery()
      if (tabName && tabName !== 'cdr_call') {
        this.$router.push({ path: '/index/call/' + tabName })
      }
      this.search[this.activeName].isChildren.adv.badgeList = {}
      this.search[this.activeName].pagination.currentPage = 1
      if (tabName === 'cdr_call' || tabName === 'cdr_outbound') {
        return false
      }
      this.quickSelect('week') // tab切换的时候，默认查询近一周的数据
      this.setQuickSeachTitle('week')
    },
    turnPage(pageNum) {
      // 翻页
      this.allCount = 0
      if (this.search.isSearch && pageNum < 2) {
        this.search.isSearch = false
        return
      }
      this.search.isSearch = false
      let form = this.search[this.activeName].isChildren.adv.form
      this.search[this.activeName].pagination.currentPage = pageNum
      this.loading = true
      let morePage =
        pageNum >= this.pages ? Math.floor(pageNum / this.pages + 1) : 1
      this.getCallList(
        this.$store,
        morePage,
        this.activeName,
        pageNum,
        form
      ).then(() => {
        this.loading = false
        this.$router.push({ path: '/index/call/' + this.activeName })
      })
    },
    handlerSelectChange(selectObj) {
      // 高级搜索的下拉框change的时候
      let selectName = selectObj.selectName
      let currentTab = this.search[this.activeName]
      this.search.isAdvSearch = false
      if (
        (selectName === 'owner' ||
        selectName === 'ownercom' ||
        selectName === 'ownerdep')&& selectObj.name && selectObj.name === 'ownercom'
      ) {
        if (selectObj.selectName === 'owner') {
          currentTab.isChildren.adv.form.DISPOSAL_AGENT = null
          currentTab.isChildren.adv.form.ownercom = null
          currentTab.isChildren.adv.form.ownerdep = null
          currentTab.isChildren.adv.form.DISPOSAL_AGENT = selectObj.selectValue
        } else {
          currentTab.isChildren.adv.form.DISPOSAL_AGENT = null
          currentTab.isChildren.adv.form.ownercom = null
          currentTab.isChildren.adv.form.ownerdep = null
          currentTab.isChildren.adv.form[selectObj.selectName] =
            selectObj.selectValue
        }
      }
      if ((selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') && selectObj.name && selectObj.name === 'REF_DISPOSAL_AGENT') {
        if (selectObj.selectName === 'owner') {
          currentTab.isChildren.adv.form.REF_DISPOSAL_AGENT = null
          currentTab.isChildren.adv.form.ownercomRefDisposalAgent = null
          currentTab.isChildren.adv.form.ownerdepRefDisposalAgent = null
          currentTab.isChildren.adv.form.REF_DISPOSAL_AGENT = selectObj.selectValue
        } else {
          currentTab.isChildren.adv.form.REF_DISPOSAL_AGENT = null
          currentTab.isChildren.adv.form.ownercomRefDisposalAgent = null
          currentTab.isChildren.adv.form.ownerdepRefDisposalAgent = null
          currentTab.isChildren.adv.form[[selectName + 'RefDisposalAgent']] = selectObj.selectValue
        }
      }
      if (selectName === "multiCallLabel") {
        if (Array.isArray(selectObj.selectValue)) {
            if(selectObj.selectValue.length>0){
              let callLabelArr = [] //传参用
              let callLabelSelectArr = [] //回显用
              selectObj.selectValue.forEach(item => {
                callLabelSelectArr.push(item)
                currentTab.isChildren.adv.form.multiCallLabels = [...new Set(callLabelSelectArr)]
                //传参所有id
                item.forEach(i=>{
                  callLabelArr.push(i._id)
                })
              })
              currentTab.isChildren.adv.form.multiLabel = [...new Set(callLabelArr)]
            }else{
               currentTab.isChildren.adv.form.multiLabel = []
               currentTab.isChildren.adv.form.multiCallLabels=[]
            }
        }
      }
      if (selectName === 'INVESTIGATE') {
        if (Array.isArray(selectObj.selectValue)) {
          let appraiseArr = []
          selectObj.selectValue.forEach(item => {
            if (item.length > 1) {
              appraiseArr.push({INVESTIGATE: item[0], CHILD_INVESTIGATE: item[1]})
            } else {
              appraiseArr.push({INVESTIGATE: item[0]})
            }
          })
          currentTab.isChildren.adv.form.appraise = appraiseArr
        }
      }
    },

    restForm() {
      this.search[this.activeName].isChildren.adv.form = {
        QUICK_QUERY_NUM: '',
        CALL_NO: '',
        CALLED_NO: '',
        ownercom: '',
        DISPOSAL_AGENT: '',
        ownerdep: '',
        ownercomRefDisposalAgent: '',
        REF_DISPOSAL_AGENT: '',
        ownerdepRefDisposalAgent: '',
        STATUS: '',
        ERROR_MEMO: [],
        INVESTIGATE: [],
        appraise: [],
        CUSTOMER_NAME: '',
        CALL_TIME_LENGTH_BEGIN: '',
        CALL_TIME_LENGTH_END: '',
        RING_TIME_LENGTH_BEGIN: '', // 振铃时长
        RING_TIME_LENGTH_END: '', // 振铃时长
        QUEUE_TIME_LENGTH_BEGIN: '',
        QUEUE_TIME_LENGTH_END: '',
        KEY_TAG: '',
        QUICK_HANGUP: '',
        multiLabel: [],
        CALL_LABEL: [],
        multiCallLabels: [],
        SQ_LABEL: '',
        OFFERING_TIME: null,
        HANGUP_TIME: null,
        isPermissions: '',
        REPEAT_CALL: [],
        HANGUP_USER: [],
        CONNECT_TYPE: '',
        IS_BUSINESS_ASSOCIATED: '',
        CALL_MEMO: '',
      }
      this.setQuickSeachTitle('week')
      let nowTime = new Date()
      let mtDate = nowTime.getTime()
      let startTime =
        getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(
          ' '
        )[0] + ' 00:00:00'
      let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
      let arr = [startTime, endTime]
      this.search[this.activeName].isChildren.adv.form.OFFERING_TIME = arr
    },
    advSearch(clearBadge) {
      // 点击高级搜索的搜索时
      window._hmt &&
        window._hmt.push([
          '_trackEvent',
          '其他统计',
          this.activeName + ' 高级搜索',
        ])
      this.allCount = 0
      this.search.isSearch = true
      this.loading = true
      let self = this
      let form = this.search[this.activeName].isChildren.adv.form
      let tempArr = {}
      let searchQuery = deepClone(form)
      if (clearBadge === true) {
        self.search.isAdvSearch = false
        self.isClear = true
        self.search[self.activeName].isChildren.nomalForm.value = ''
        // 清空高级搜索选项
        for (let key in form) {
          if (key === 'custom') {
            form.custom = {}
          } else if (key === 'REPEAT_CALL' || key === 'ERROR_MEMO') {
            form[key] = []
          } else {
            form[key] = null
          }
        }
        searchQuery = {}
        this.search[this.activeName].isChildren.adv.badgeList = {}
        this.search[this.activeName].isChildren.adv.form = {
          QUICK_QUERY_NUM: '',
          CALL_NO: '',
          CALLED_NO: '',
          ownercom: '',
          DISPOSAL_AGENT: '',
          ownerdep: '',
          ownercomRefDisposalAgent: '',
          REF_DISPOSAL_AGENT: '',
          ownerdepRefDisposalAgent: '',
          STATUS: '',
          ERROR_MEMO: [],
          INVESTIGATE: [],
          appraise: [],
          CUSTOMER_NAME: '',
          CALL_TIME_LENGTH_BEGIN: '',
          CALL_TIME_LENGTH_END: '',
          RING_TIME_LENGTH_BEGIN: '', // 振铃时长
          RING_TIME_LENGTH_END: '', // 振铃时长
          QUEUE_TIME_LENGTH_BEGIN: '',
          QUEUE_TIME_LENGTH_END: '',
          KEY_TAG: '',
          QUICK_HANGUP: '',
          multiLabel: [],
          multiCallLabels: [],
          CALL_LABEL: [],
          SQ_LABEL: '',
          OFFERING_TIME: null,
          HANGUP_TIME: null,
          isPermissions: '',
          REPEAT_CALL: [],
          HANGUP_USER: [],
          CONNECT_TYPE: '',
          IS_BUSINESS_ASSOCIATED: '',
          CALL_MEMO: '',
        }
        this.setQuickSeachTitle('week')
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let startTime =
          getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(
            ' '
          )[0] + ' 00:00:00'
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        let arr = [startTime, endTime]
        this.search[this.activeName].isChildren.adv.form.OFFERING_TIME = arr
        form.OFFERING_TIME = arr
      } else {
        self.search.isAdvSearch = true
        self.isClear = false
        let custom = searchQuery.custom
        for (let key in searchQuery) {
          // 搜索条件
          if (searchQuery[key] && key !== 'custom' && key !== 'INVESTIGATE'&&key !=='CALL_LABEL'&&key !=='multiLabel') {
            tempArr[key] = searchQuery[key]
          }
        }
        for (let i in custom) {
          searchQuery[i] = custom[i]
        }
        delete searchQuery.custom
        // 去除普通搜索的条件
        for (let key in this.search[this.activeName].isChildren.nomalForm) {
          this.search[this.activeName].isChildren.nomalForm[key] = null
        }
      }
      Promise.all([
        this.$store.dispatch('getCache', { type: 'callType' }),
        this.$store.dispatch('getCache', { type: 'callStatus' }),
        this.$store.dispatch('getCache', { type: 'queues' }),
        this.$store.dispatch('getCache', { type: 'investigate' }),
        this.$store.dispatch('getCache', { type: 'sqLabels' }),
      ]).then(([callType, callStatus, queues, investigate, sqLabels]) => {
        for (let i in tempArr) {
          if (i === 'REPEAT_CALL') {
            if (tempArr[i].length > 1) {
              tempArr[i] = this.$t('call.repeatCallAll')
            } else if (tempArr[i].length < 1) {
              delete tempArr[i]
            } else {
              for (let m in tempArr[i]) {
                if (tempArr[i][m] === '24h') {
                  tempArr[i] = this.$t('call.repeatCall24h') // 这负责改字
                } else if (tempArr[i][m] === '48h') {
                  tempArr[i] = this.$t('call.repeatCall48h')
                }
              }
            }
          }
          if (i === 'STATUS') {
            for (let j = 0; j < callStatus.length; j++) {
              if (callStatus[j].code_value === tempArr[i]) {
                tempArr[i] = callStatus[j].code_name
                break
              }
            }
          } else if (i === 'ERROR_MEMO') {
            if (i === 'ERROR_MEMO') {
              if (tempArr[i].length > 1) {
                let name = ''
                for (let j = 0; j < queues.length; j++) {
                  for (let k = 0; k < tempArr[i].length; k++) {
                    if (tempArr[i][k].indexOf(queues[j].Exten) > -1) {
                      name += queues[j].DisplayName + ' '
                      break
                    }
                  }
                }
                tempArr[i] = name
              } else if (tempArr[i].length < 1) {
                delete tempArr[i]
              } else {
                for (let j = 0; j < queues.length; j++) {
                  if (queues[j].Exten === tempArr[i].toString()) {
                    tempArr[i] = queues[j].DisplayName
                    break
                  }
                }
              }
            }
          } else if (i === 'appraise') {
            let appraiseStr = ''
            tempArr[i].forEach(item => {
              if (item.INVESTIGATE === 'unevaluated') {
                appraiseStr += `${this.$t('public.unevaluated')} 、`
              }
              investigate.forEach(item2 => {
                if (item2.value === item.INVESTIGATE) {
                  if (item.CHILD_INVESTIGATE && item2.children) {
                    item2.children.forEach((item3) => {
                      if (item3.value === item.CHILD_INVESTIGATE) {
                        appraiseStr += `${item2.name} > ${item3.name} 、`
                        return false
                      }
                    })
                  } else {
                    appraiseStr += `${item2.name} 、`
                  }
                  return false
                }
              })
            })
            if (appraiseStr) {
              tempArr[i] = appraiseStr.substring(0, appraiseStr.length - 1)
            } else {
              delete tempArr[i]
            }
          } else if (i === 'CONNECT_TYPE') {
            for (let j = 0; j < callType.length; j++) {
              if (callType[j].code_value === tempArr[i]) {
                tempArr[i] = callType[j].code_name
                break
              }
            }
          } else if (i === 'CUSTOMER_NAME') {
            if (tempArr[i] === true || tempArr[i] === 'true') {
              tempArr[i] = this.$t('public.locatedCustomer')
            }
          } else if (i === 'SQ_LABEL') {
            for (let j = 0; j < sqLabels.length; j++) {
              if (sqLabels[j]._id === tempArr[i]) {
                tempArr[i] = sqLabels[j].name
                break
              }
            }
          } else if (
            i === 'CALL_TIME_LENGTH_BEGIN' ||
            i === 'CALL_TIME_LENGTH_END'
          ) {
            if (tempArr.CALL_TIME_LENGTH) {
              tempArr.CALL_TIME_LENGTH += ' ' + tempArr[i]
            } else {
              tempArr.CALL_TIME_LENGTH = tempArr[i]
            }
            delete tempArr[i]
          } else if (
            i === 'QUEUE_TIME_LENGTH_BEGIN' ||
            i === 'QUEUE_TIME_LENGTH_END'
          ) {
            if (tempArr.QUEUE_TIME_LENGTH) {
              tempArr.QUEUE_TIME_LENGTH += ' ' + tempArr[i]
            } else {
              tempArr.QUEUE_TIME_LENGTH = tempArr[i]
            }
            delete tempArr[i]
          } else if (
            i === 'RING_TIME_LENGTH_BEGIN' ||
            i === 'RING_TIME_LENGTH_END'
          ) {
            if (tempArr.RING_TIME_LENGTH) {
              tempArr.RING_TIME_LENGTH += ' ' + tempArr[i]
            } else {
              tempArr.RING_TIME_LENGTH = tempArr[i]
            }
            delete tempArr[i]
          } else if (i === 'KEY_TAG' || i === 'QUICK_HANGUP') {
            if (tempArr[i] === true || tempArr[i] === 'true') {
              tempArr[i] = this.$t('call.fastHangUpOption')
            } else {
              tempArr[i] = this.$t('call.noFastHangUpOption')
            }
          } else if (i === 'IS_BUSINESS_ASSOCIATED') {
            if (tempArr[i] === true || tempArr[i] === 'true') {
              tempArr[i] = this.$t('public.yes')
            } else {
              tempArr[i] = this.$t("public.no")
            }
          } else if (i === 'multiCallLabels') {
            if (tempArr[i].length < 1) {
              delete tempArr[i]
            } else {
              let labelArr = form.multiLabel || []
              let labelStr = ''
              for (let m in tempArr[i]) {
                let itemLabel = tempArr[i][m]
                labelArr = m < 1 ? [] : labelArr // m 为0 的时候重置labelArr
                labelStr = m < 1 ? '' : labelStr // m 为0 的时候重置labelStr
                self.multiTempCom = m < 1 ? [] : self.multiTempCom // m 为0 的时候重置multiTempCom
                itemLabel.forEach(item=>{
                  labelArr.push(item._id)
                })
                if(itemLabel.length>1){
                  self.multiTempCom = []
                  itemLabel.forEach(item=>{
                    self.multiTempCom.push(item.name)
                  })
                  //有子级的时候拼>
                  self.multiTempCom.forEach((i) => {
                    labelStr += i + '>'
                  })
                  labelStr = labelStr.substring(0, labelStr.length - 1) + '、'
                }else{
                  itemLabel.forEach(item=>{
                    labelStr += item.name + '、'
                  })
                }
              }
              if(labelArr.includes('')){
                labelArr = []
                delete tempArr[i]
              }else{
                tempArr[i] = labelStr.substring(0, labelStr.length - 1)
              }
              form.multiLabel = labelArr
            }
          }else if (
            (i === 'OFFERING_TIME' || i === 'HANGUP_TIME') &&
            Array.isArray(tempArr[i])
          ) {
            if (!tempArr[i] || tempArr[i].length === 0) {
              delete tempArr[i]
              continue
            }
            if (
              (tempArr[i][0] === null && tempArr[i][1] === null) ||
              (tempArr[i].length === 1 && tempArr[i][0] === null)
            ) {
              delete tempArr[i]
              continue
            }
            if (tempArr[i][0]) {
              tempArr[i] = getFormatDateTime(form[i][0])
            }
            if (tempArr[i][1]) {
              tempArr[i] += ' ' + getFormatDateTime(form[i][1])
            }
          } else if (i === 'ownercom') {
            if (tempArr[i].match(/__/)) {
              self.temporaryCom = tempArr[i]
              form.ownercom = tempArr[i]
              tempArr[i] = tempArr[i].substr(tempArr[i].indexOf('__') + 2)
            }else {
              tempArr[i] = self.temporaryCom.substr(
                self.temporaryCom.indexOf('__') + 2
              )
            }
          } else if (i === 'ownerdep') {
            if (tempArr[i].match(/__/)) {
              self.temporaryDep = tempArr[i]
              form.ownerdep = tempArr[i].substr(0, tempArr[i].indexOf('__'))
              tempArr[i] = tempArr[i].substr(tempArr[i].indexOf('__') + 2)
            } else {
              tempArr[i] = self.temporaryDep.substr(
                self.temporaryDep.indexOf('__') + 2
              )
            }
          } else if (i === 'DISPOSAL_AGENT') {
            if (tempArr[i].match(/__/)) {
              self.temporaryAgent = tempArr[i]
              form.DISPOSAL_AGENT = tempArr[i].substr(
                0,
                tempArr[i].indexOf('__')
              )
              tempArr[i] = tempArr[i].substr(tempArr[i].indexOf('__') + 2)
            } else {
              tempArr[i] = self.temporaryAgent.substr(
                self.temporaryAgent.indexOf('__') + 2
              )
            }
          }else if (i === 'HANGUP_USER') {
            let hangupUser = [
              {
                label: self.$t('call.inHangUpC'),
                value: 'customer',
              },
              {
                label:
                  self.$t('call.inHangUpA') +
                  '（' +
                  self.$t('call.Activehangup') +
                  '）',
                value: 'agent',
              },
              {
                label:
                  self.$t('call.inHangUpA') +
                  '（' +
                  self.$t('call.CauseOfHangingUp3') +
                  '）',
                value: 'agent_satisfaction',
              },
              {
                label: self.$t('call.inHangUpT'),
                value: 'agent_transfer',
              },
              {
                label:
                  self.$t('call.inHangUpA') +
                  '（' +
                  self.$t('call.rootGua') +
                  '）',
                value: 'agent_loot',
              },
              {
                label:
                  self.$t('call.inHangUpA') +
                  '（' +
                  self.$t('call.forceGua') +
                  '）',
                value: 'agent_force',
              },
              {
                label: this.$t('call.inHangUpD'),
                value: 'timeout_not_answered',
              },
              {
                label: self.$t('call.inHangOutside'),
                value: 'outLine',
              },
            ]
            if (tempArr[i].length > 1) {
              let name = ''
              for (let j = 0; j < hangupUser.length; j++) {
                for (let k = 0; k < tempArr[i].length; k++) {
                  if (tempArr[i][k] === hangupUser[j].value) {
                    name += hangupUser[j].label + ' '
                    break
                  }
                }
              }
              tempArr[i] = name
            } else if (tempArr[i].length < 1) {
              delete tempArr[i]
            } else {
              for (let j = 0; j < hangupUser.length; j++) {
                if (hangupUser[j].value === tempArr[i].toString()) {
                  tempArr[i] = hangupUser[j].label
                  break
                }
              }
            }
            }
          else if (i === 'REF_DISPOSAL_AGENT') {
            if (tempArr[i].match(/__/)) {
              self.transferBeforeSeat = tempArr[i]
              form.REF_DISPOSAL_AGENT = tempArr[i].substr(0, tempArr[i].indexOf('__'))
              tempArr[i] = tempArr[i].substr(tempArr[i].indexOf('__') + 2)
            } else {
              tempArr[i] = self.transferBeforeSeat.substr(
                self.transferBeforeSeat.indexOf('__') + 2
              )
            }
          }else if (i === 'ownercomRefDisposalAgent') {
            if (tempArr[i].match(/__/)) {
              self.transferBeforeSeatCom = tempArr[i]
              form.ownercomRefDisposalAgent = tempArr[i].substr(0, tempArr[i].indexOf('__'))
              tempArr[i] = tempArr[i].substr(tempArr[i].indexOf('__') + 2)
            } else {
              tempArr[i] = self.transferBeforeSeatCom.substr(
                self.transferBeforeSeatCom.indexOf('__') + 2
              )
            }
          } else if (i === 'ownerdepRefDisposalAgent') {
            if (tempArr[i].match(/__/)) {
              self.transferBeforeSeatDep = tempArr[i]
              form.ownerdepRefDisposalAgent = tempArr[i].substr(0, tempArr[i].indexOf('__'))
              tempArr[i] = tempArr[i].substr(tempArr[i].indexOf('__') + 2)
            } else {
              tempArr[i] = self.transferBeforeSeatDep.substr(
                self.transferBeforeSeatDep.indexOf('__') + 2
              )
            }
          }
        }
        this.search[this.activeName].isChildren.adv.badgeList = tempArr
        this.search[this.activeName].isChildren.adv.condition = deepClone(form)
        this.search[this.activeName].pagination.currentPage = 1
        let _form = deepClone(form)
        if (_form.CUSTOMER_NAME && _form.CUSTOMER_NAME === 'Unknown customer') {
          _form.CUSTOMER_NAME = '未知客户'
        } else if (
          _form.CUSTOMER_NAME &&
          _form.CUSTOMER_NAME === 'Multiple matching customers'
        ) {
          _form.CUSTOMER_NAME = '多个匹配客户'
        }
        for(let key in _form){
          if(key=='CALL_LABEL'||key=='multiCallLabels'){
            delete _form[key]
          }
        }
        for(let key in this.search[this.activeName].isChildren.adv.condition){
          if(key=='CALL_LABEL'||key=='multiCallLabels'){
            delete this.search[this.activeName].isChildren.adv.condition[key]
          }
        }
        if(_form.multiLabel&&_form.multiLabel.length>0&&_form.multiLabel[0]!=='noLabel'){
          _form.callFlag=true
        }
        this.getCallList(this.$store, 1, this.activeName, 1, _form).then(() => {
          this.loading = false
          this.$router.push({ path: '/index/call/' + this.activeName })
        })
      })
    },
    quickSelect(value) {
      this.allCount = 0
      this.search.isSearch = true
      this.loading = true
      if (this.search.isAdvSearch && value === null) {
        return
      }
      this.search.isAdvSearch = false
      let form = {
        QUICK_QUERY_NUM: '',
        CALL_NO: '',
        CALLED_NO: '',
        CONNECT_TYPE: '',
        ownercom: '',
        DISPOSAL_AGENT: '',
        ownerdep: '',
        ownercomRefDisposalAgent: '',
        REF_DISPOSAL_AGENT: '',
        ownerdepRefDisposalAgent: '',
        STATUS: '',
        ERROR_MEMO: [],
        INVESTIGATE: [],
        appraise: [],
        CUSTOMER_NAME: '',
        CALL_TIME_LENGTH_BEGIN: '',
        CALL_TIME_LENGTH_END: '',
        RING_TIME_LENGTH_BEGIN: '', // 振铃时长
        RING_TIME_LENGTH_END: '',
        QUEUE_TIME_LENGTH_BEGIN: '',
        QUEUE_TIME_LENGTH_END: '',
        KEY_TAG: '',
        QUICK_HANGUP: '',
        multiLabel: [],
        CALL_LABEL: [],
        multiCallLabels: [],
        SQ_LABEL: '',
        HANGUP_TIME: null,
        isPermissions: '',
        REPEAT_CALL: [],
        HANGUP_USER: [],
        IS_BUSINESS_ASSOCIATED: '',
        CALL_MEMO: '',
      }
      if (value === 'mycall') {
        form.ownercom = 'myself__flag'
        if (
          this.search[this.activeName].isChildren.adv.form &&
          this.search[this.activeName].isChildren.adv.form.OFFERING_TIME
        ) {
          form.OFFERING_TIME =
            this.search[this.activeName].isChildren.adv.form.OFFERING_TIME ||
            null
        }
      } else {
        form.ownercom = ''
        let time = this.searchDataReturn(value)
        if (time) {
          form.OFFERING_TIME = [
            new Date(time.createTime$begin),
            new Date(time.createTime$end),
          ]
        }
      }
      if (this.search[this.activeName].isChildren.nomalForm.query) {
        form.QUICK_QUERY_NUM = this.search[
          this.activeName
        ].isChildren.nomalForm.query
      }
      this.setQuickSeachTitle(value)
      this.search[this.activeName].isChildren.adv.form = form // 快捷搜索时，清空高级搜索项
      this.search[this.activeName].isChildren.adv.badgeList = {} // 快捷搜索时，清空回显的搜索条件
      this.search[this.activeName].pagination.currentPage = 1
      this.search[this.activeName].isChildren.adv.condition = form
      this.getCallList(this.$store, 1, this.activeName, 1, form).then(() => {
        this.loading = false
        this.$router.push({ path: '/index/call/' + this.activeName })
      })
    },
    /*
     * 快捷搜索时间
     * */
    searchDataReturn(value) {
      let nowTime = new Date()
      let mtDate = nowTime.getTime()
      let startTime = ''
      let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
      if (value === 'week') {
        // 近一周
        startTime =
          getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(
            ' '
          )[0] + ' 00:00:00'
      } else if (value === 'today') {
        // 今天
        startTime =
          getFormatDateTime(new Date(mtDate)).split(' ')[0] + ' 00:00:00'
      } else if (value === 'yesterday') {
        // 昨天
        startTime =
          getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] +
          ' 00:00:00'
        endTime =
          getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] +
          ' 23:59:59'
      } else if (value === 'month') {
        // 近一月
        startTime =
          getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 30)).split(
            ' '
          )[0] + ' 00:00:00'
      } else {
        endTime = ''
      }
      if (startTime && endTime) {
        let searchQuery = {
          createTime$begin: startTime,
          createTime$end: endTime,
        }
        return searchQuery
      } else {
        return null
      }
    },
    inputSearch(phoneNum) {
      // 表单搜索
      this.allCount = 0
      this.search.isSearch = true
      this.loading = true
      let form = {
        QUICK_QUERY_NUM: '',
        CALL_NO: '',
        CALLED_NO: '',
        CONNECT_TYPE: '',
        ownercom: '',
        DISPOSAL_AGENT: '',
        ownercomRefDisposalAgent: '',
        REF_DISPOSAL_AGENT: '',
        ownerdepRefDisposalAgent: '',
        ownerdep: '',
        STATUS: '',
        ERROR_MEMO: [],
        INVESTIGATE: [],
        appraise: [],
        CUSTOMER_NAME: '',
        CALL_TIME_LENGTH_BEGIN: '',
        CALL_TIME_LENGTH_END: '',
        RING_TIME_LENGTH_BEGIN: '', // 振铃时长
        RING_TIME_LENGTH_END: '',
        QUEUE_TIME_LENGTH_BEGIN: '',
        QUEUE_TIME_LENGTH_END: '',
        KEY_TAG: '',
        QUICK_HANGUP: '',
        multiLabel: [],
        CALL_LABEL: [],
        multiCallLabels: [],
        SQ_LABEL: '',
        HANGUP_TIME: null,
        isPermissions: '',
        REPEAT_CALL: [],
        HANGUP_USER: [],
        IS_BUSINESS_ASSOCIATED: '',
        CALL_MEMO: '',
      }
      if (!this.search[this.activeName].isChildren.adv.form.OFFERING_TIME) {
        this.setQuickSeachTitle('week')
        let nowTime = new Date()
        let mtDate = nowTime.getTime()
        let startTime =
          getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(
            ' '
          )[0] + ' 00:00:00'
        let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        let arr = [startTime, endTime]
        this.search[this.activeName].isChildren.adv.form.OFFERING_TIME = arr
      } else {
        form.OFFERING_TIME = this.search[
          this.activeName
        ].isChildren.adv.form.OFFERING_TIME
      }
      this.search[this.activeName].pagination.currentPage = 1
      this.search[this.activeName].isChildren.adv.form = form //  input搜索时，清空高级搜索项
      this.search[this.activeName].isChildren.adv.badgeList = {} // input搜索时，清空回显的搜索条件
      this.search[this.activeName].isChildren.adv.condition = form
      form.QUICK_QUERY_NUM = phoneNum // 快捷搜索的条件不带到高级搜索里面，若是把当前条件配置成不可见，会自动带上条件搜索。
      this.getCallList(this.$store, 1, this.activeName, 1, form).then(() => {
        this.loading = false
        this.$router.push({ path: '/index/call/' + this.activeName })
      })
    },
    removeBadge() {
      // 去除搜索条件
      this.advSearch(true)
      this.clearChecked = Math.random() + ''
    },
    handleRefresh() {
      // 刷新
      this.allCount = 0
      this.search.isSearch = true
      this.loading = true
      this.search[this.activeName].pagination.currentPage = 1
      let form = this.search[this.activeName].isChildren.adv.form
      this.getCallList(this.$store, 1, this.activeName, 1, form).then(() => {
        this.loading = false
      })
    },
    handleConfirmNewItemsConfig({ data: formItemsConfig, done }) {
      var formItemsConfigs = deepClone(this.formItemsConfigs)
      formItemsConfigs[this.activeName] = formItemsConfig

      this.$store
        .dispatch('saveAdvSearchConfig', {
          searchType: 'CallCardGroup',
          config: formItemsConfigs,
        })
        .then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
    },
  },
  computed: {
    shortcutOpen: {
      get(){
        return this.$store.state.config.shortcutKey.openShortcutKey.commonSwitch
      },
      set(v) { }
    },
    getSessionCallTimeLimit() {
      //  当为-1时，去掉时间范围限制
      //  当没有值或者为0时，取时间范围限制为1个月
      //  如果值为1，则限制1个月
      //  如果值为2，则限制2个月，等等
      //  此限制在计费配置 （账户管理=》设置 =》通话记录查询设置）
      return this.$store.state.session.account.recordRange &&
        this.$store.state.session.account.recordRange.recordRangeMonth
        ? this.$store.state.session.account.recordRange.recordRangeMonth
        : 1
    },
    currentPage() {
      if (this.$route.path.split('/')[2] === 'call') {
        return this.search[this.activeName].pagination.currentPage
      } else {
        return 1
      }
    },
    isCallLeakSheet() {
      return isHasMenu('call_sheet_leak', this.$store.state.session.user)
    },
    isCallExport() {
      return (
        isHasMenu('batch_export_record_task', this.$store.state.session.user) ||
        isHasMenu('batch_export_cdr_task', this.$store.state.session.user)
      )
    },
    cardList() {
      // 获取卡片的list
      if (this.activeName && this.$route.path.split('/')[2] === 'call') {
        if (this.$store.state.call && this.$store.state.call.callList) {
          if (this.$store.state.call.callList[this.activeName]) {
            let list = this.$store.state.call.callList[this.activeName].list || []
            return JSON.parse(JSON.stringify(list))
          } else {
            return []
          }
        } else {
          return []
        }
      } else {
        return []
      }
    },
    count() {
      // count 条数
      if (this.activeName && this.$route.path.split('/')[2] === 'call') {
        let countNum = this.$store.state.call.callList[this.activeName].count || 0
        return countNum
      } else {
        return 0
      }
    },
    moreFlag() {
      // 获取是否有查看更多
      if (this.activeName && this.$route.path.split('/')[2] === 'call') {
        if (this.$store.state.call.callList[this.activeName].more) {
          return this.$store.state.call.callList[this.activeName].more
        } else {
          return false
        }
      } else {
        return false
      }
    },
    tabPanes() {
      // tab上的未读数
      let cdrCallNum = this.$store.state.call.unReadCdr
      let pendingNum = this.$store.state.call.current.cdr_pending.pendingNumber
      let outBoundCount = 0
      if (
        this.$store.state.call.callList &&
        this.$store.state.call.callList.cdr_outbound.list
      ) {
        outBoundCount = this.$store.state.call.callList.cdr_outbound.list.length
      }
      let newNum = ''
      if (cdrCallNum && cdrCallNum > 0) {
        newNum = cdrCallNum
      }
      return [
        { name: this.$t('call.cdrCall') + newNum, type: 'cdr_call' },
        {
          name: this.$t('call.cdrOutbound') + outBoundCount,
          type: 'cdr_outbound',
        },
        { name: this.$t('call.cdrPending') + pendingNum, type: 'cdr_pending' },
        { name: this.$t('call.cdrAll'), type: 'cdr_all' }
      ]
    },
    totalPage() {
      // 页数
      if (this.activeName && this.$route.path.split('/')[2] === 'call') {
        return (
          Math.ceil(
            this.$store.state[this.type][this.type + 'List'][this.activeName]
              .count / 10
          ) || 0
        )
      } else {
        return 0
      }
    }
  },
  activated() {
    // keep-alive 组件激活时才进行一下操作，否则会出现tab下划线位置不对，卡片选中2个，右侧组件加载错误的问题
    let routeArr = this.$route.path.split('/')
    this.activeName = routeArr[3] // 在其他模块操作时，点击来电浏览器提醒
    if (this.$route.path === '/index/call/cdr_all/callExport') {
      this.loading = false
    }
    this.$nextTick(() => {
      if (
        this.$route.query &&
        this.$route.query.pending &&
        this.$route.query.pending === 'leakAssignMsg'
      ) {
        this.$router.push('/index/call/cdr_pending')
        this.$store.commit('BLANK', 'cdr_pending') // 设置通话的空白页
      }
    })
  },
  provide() {
    // AdvancedSearchConfigDialog.vue  inject接收父组件传递的itemsDisabled
    return {
      itemsDisabled: {
        cdr_pending: {
          OFFERING_TIME: true,
        },
        cdr_all: {
          OFFERING_TIME: true,
        },
      },
    }
  },
  beforeMount() {
    Promise.all([
      this.$store.dispatch('getCache', { type: 'callType' }), // 通话类型
      this.$store.dispatch('getCache', { type: 'callStatus' }), // 通话状态
      this.$store.dispatch('getCache', { type: 'queues' }), // 技能组
      this.$store.dispatch('getCache', { type: 'investigate' }), // 满意度
      this.$store.dispatch('getCache', { type: 'sqLabels' }), // 服务质量标签
      this.$store.dispatch('getCache', { type: 'custTmpls' }), // 客户配置
      this.$store.dispatch('getCache', { type: 'callLabel' }), // 通话标签
      this.$store.dispatch('getCache', { type: 'serviceNo' }), // 服务号
      this.$store.dispatch('getAdvSearchConfig', {
        searchType: 'CallCardGroup',
      }), // 高级搜索布局配置
    ]).then(
      ([
        callType,
        callStatus,
        queues,
        investigate,
        sqLabels,
        custTmpls,
        callLabel,
        serviceNo,
        config
      ]) => {
        let callServerNo = []
        for (let key in serviceNo) {
          let value = ''
          if (serviceNo[key].DisplayName) {
            value = '[' + serviceNo[key].DisplayName + ']'
          }
          value += serviceNo[key].Exten
          let peer = {
            exten: serviceNo[key].Exten,
            value: value
          }
          callServerNo.push(peer)
        }      
        // 满意度评价，增加未评价项
        let satisfactionFirst = [{label: this.$t('public.unevaluated'), value: 'unevaluated'}]
        this.callServerNo = callServerNo || []
        this.search.cdr_all.isChildren.adv.advSearchOptions.localed = [
          {label: this.$t('public.quickSearch'), name: 'QUICK_QUERY_NUM', inputType: 'input', placehoder: this.$t('call.enterCallnumOrCallednumForQuery')},
          {label: this.$t('public.calling'), name: 'CALL_NO', inputType: 'serverNo', type: 'searchCaseInsensitive'},
          {label: this.$t('public.called'), name: 'CALLED_NO', inputType: 'serverNo', type: 'searchCaseInsensitive'},
          {label: this.$t('call.callRingSeat'), name: 'ownercom', inputType: 'owner'},
          {label: this.$t('call.callStatusType'), name: 'STATUS', filterable: true, inputType: 'select', data: generateNewKeyValue(callStatus, ['code_name', 'code_value'], ['label', 'value'], this.$t('public.all'), true)},
          {label: this.$t('public.satisfaction'), name: 'INVESTIGATE', inputType: 'multipleCascader', data: generateNewKeyValue(investigate, ['name', 'value', 'children'], ['label', 'value', 'children'], satisfactionFirst)},
          {label: this.$t('public.locationCustomer'), name: 'CUSTOMER_NAME', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('public.unknownCustomer'), value: this.$t('public.unknownCustomer')}, {label: this.$t('public.locatedCustomer'), value: 'true'}, {label: this.$t('public.locatedCustomers'), value: this.$t('public.locatedCustomers')}]},
          {label: this.$t('public.callTime'), name: 'OFFERING_TIME', inputType: 'time', hideClose: true},
          {label: this.$t('call.sign'), name: 'KEY_TAG', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('public.yes'), value: 'true'}, {label: this.$t('public.no'), value: 'false'}]},
          {label: this.$t('call.callTime'), name: 'CALL_TIME_LENGTH_BEGIN', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.callTime'), name: 'CALL_TIME_LENGTH_END', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.queueLen'), name: 'QUEUE_TIME_LENGTH_BEGIN', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.queueLen'), name: 'QUEUE_TIME_LENGTH_END', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('public.queues'), multiple: true, filterable: true, name: 'ERROR_MEMO', inputType: 'select', data: generateNewKeyValue(queues, ['DisplayName', 'Exten'], ['label', 'value'])},
          {label: this.$t('call.ringLength'), name: 'RING_TIME_LENGTH_BEGIN', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.ringLength'), name: 'RING_TIME_LENGTH_END', inputType: 'rangeInput', validateType: 'Number3'},
          // {label: this.$t('call.handUpTime'), name: 'HANGUP_TIME', inputType: 'time'},
          {
            label: this.$t('call.SQLabel'),
            name: 'SQ_LABEL',
            filterable: true,
            inputType: 'select',
            data: generateNewKeyValue(
              sqLabels,
              ['name', '_id'],
              ['label', 'value'],
              this.$t('public.all')
            ),
          },
          {
            label: this.$t('call.callNumber'),
            inputType: 'input',
            name: 'CALL_SHEET_ID'
          },
          {
            label: this.$t("call.repeatCall"),
            name: "REPEAT_CALL",
            multiple: true,
            inputType: 'select',
            data: [
              { label: this.$t('call.repeatCall24hNum'), value: '24h' },
              { label: this.$t('call.repeatCall48hNum'), value: '48h' },
            ]
          },
          {
            label: this.$t('public.callLabel'),
            name: 'CALL_LABEL',
            filterable: true,
            inputType: 'cascaderMulti'
          },
          {
            label: this.$t('call.inHangUpUser'),
            name: 'HANGUP_USER',
            filterable: true,
            multiple: true,
            inputType: 'select',
            collapseTags: true,
            data: [
              { label: this.$t("call.inHangUpC"), value: "customer" },
              {
                label:
                  this.$t('call.inHangUpA') +
                  '（' +
                  this.$t('call.Activehangup') +
                  '）',
                value: 'agent',
              },
              {
                label:
                  this.$t('call.inHangUpA') +
                  '（' +
                  this.$t('call.CauseOfHangingUp3') +
                  '）',
                value: 'agent_satisfaction',
              },
              { label: this.$t('call.inHangUpT'), value: 'agent_transfer' },
              {
                label:
                  this.$t('call.inHangUpA') +
                  '（' +
                  this.$t('call.rootGua') +
                  '）',
                value: 'agent_loot',
              },
              {
                label:
                  this.$t('call.inHangUpA') +
                  '（' +
                  this.$t('call.forceGua') +
                  '）',
                value: 'agent_force',
              },
              { label: this.$t('call.inHangOutside'), value: 'outLine' },
              {
                label: this.$t('call.inHangUpD'),
                value: 'timeout_not_answered',
              }
            ]
          },
          {
            label: this.$t('call.callType'),
            name: 'CONNECT_TYPE',
            inputType: 'select',
            data: generateNewKeyValue(
              callType,
              ['code_name', 'code_value'],
              ['label', 'value'],
              this.$t('public.all'),
              true
            )
          },
          {
            label: this.$t('call.RelatedJobList'),
            name: 'IS_BUSINESS_ASSOCIATED',
            inputType: 'select',
            data: [
              { label: this.$t('public.all'), value: '' },
              { label: this.$t('public.yes'), value: 'true' },
              { label: this.$t('public.no'), value: 'false' }
            ]
          },
          {
            label: this.$t('call.fastHangup'),
            name: 'QUICK_HANGUP',
            inputType: 'select',
            data: [
              { label: this.$t('public.all'), value: '' },
              { label: this.$t('call.fastHangUpOption'), value: 'true' },
              { label: this.$t('call.noFastHangUpOption'), value: 'false' }
            ]
          },
          {
            label: this.$t('public.note'),
            name: 'CALL_MEMO',
            inputType: 'input',
          },
          {label: this.$t('call.transferBeforeSeat'), name: 'REF_DISPOSAL_AGENT', inputType: 'owner'},
        ]
        this.search.cdr_pending.isChildren.adv.advSearchOptions.localed = [
          {label: this.$t('public.quickSearch'), name: 'QUICK_QUERY_NUM', inputType: 'input', placehoder: this.$t('call.enterCallnumOrCallednumForQuery')},
          {label: this.$t('public.calling'), name: 'CALL_NO', inputType: 'serverNo'},
          {label: this.$t('public.called'), name: 'CALLED_NO', inputType: 'serverNo'},
          {label: this.$t('call.callStatusType'), name: 'STATUS', filterable: true, inputType: 'select', data: generateNewKeyValue(callStatus, ['code_name', 'code_value'], ['label', 'value'], this.$t('public.all'), true)},
          {label: this.$t('public.satisfaction'), name: 'INVESTIGATE', inputType: 'multipleCascader', data: generateNewKeyValue(investigate, ['name', 'value', 'children'], ['label', 'value', 'children'], satisfactionFirst, false, 'investigate')},
          {label: this.$t('public.locationCustomer'), name: 'CUSTOMER_NAME', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('public.unknownCustomer'), value: this.$t('public.unknownCustomer')}, {label: this.$t('public.locatedCustomer'), value: 'true'}, {label: this.$t('public.locatedCustomers'), value: this.$t('public.locatedCustomers')}]},
          {label: this.$t('public.callTime'), name: 'OFFERING_TIME', inputType: 'time'},
          {label: this.$t('call.sign'), name: 'KEY_TAG', inputType: 'select', data: [{label: this.$t('public.all'), value: ''}, {label: this.$t('public.yes'), value: 'true'}, {label: this.$t('public.no'), value: 'false'}]},
          {label: this.$t('call.repeatCall'), name: 'REPEAT_CALL', multiple: true, inputType: 'select', data: [{label: this.$t('call.repeatCall24hNum'), value: '24h'}, {label: this.$t('call.repeatCall48hNum'), value: '48h'}]},
          {label: this.$t('call.callTime'), name: 'CALL_TIME_LENGTH_BEGIN', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.callTime'), name: 'CALL_TIME_LENGTH_END', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.queueLen'), name: 'QUEUE_TIME_LENGTH_BEGIN', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.queueLen'), name: 'QUEUE_TIME_LENGTH_END', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('public.queues'), multiple: true, filterable: true, name: 'ERROR_MEMO', inputType: 'select', data: generateNewKeyValue(queues, ['DisplayName', 'Exten'], ['label', 'value'])},
          {label: this.$t('call.ringLength'), name: 'RING_TIME_LENGTH_BEGIN', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.ringLength'), name: 'RING_TIME_LENGTH_END', inputType: 'rangeInput', validateType: 'Number3'},
          {label: this.$t('call.inHangUpUser'), name: 'HANGUP_USER', filterable: true, multiple: true, inputType: 'select', collapseTags: true, data: [{label: this.$t('call.inHangUpC'), value: 'customer'}, {label: this.$t('call.inHangUpA') + '（' + this.$t('call.Activehangup') + '）', value: 'agent'}, {label: this.$t('call.inHangUpA') + '（'+ this.$t('call.CauseOfHangingUp3') + '）', value: 'agent_satisfaction'}, {label: this.$t('call.inHangUpT') , value: 'agent_transfer'}, {label: this.$t('call.inHangUpA') + '（' + this.$t('call.rootGua') + '）', value: 'agent_loot'}, {label: this.$t('call.inHangUpA') + '（' + this.$t('call.forceGua') + '）', value: 'agent_force'}, {label: this.$t('call.inHangOutside'), value: 'outLine'}, {label: this.$t('call.inHangUpD') , value: 'timeout_not_answered'}]},
           {label: this.$t('call.handUpTime'), name: 'HANGUP_TIME', inputType: 'time'},
          {
            label: this.$t('public.callLabel'),
            name: 'CALL_LABEL',
            filterable: true,
            inputType: 'cascaderMulti'
          },
          {
            label: this.$t('call.SQLabel'),
            name: 'SQ_LABEL',
            filterable: true,
            inputType: 'select',
            data: generateNewKeyValue(
              sqLabels,
              ['name', '_id'],
              ['label', 'value'],
              this.$t('public.all')
            )
          },
          {
            label: this.$t('call.callNumber'),
            inputType: 'input',
            name: 'CALL_SHEET_ID'
          },
          {
            label: this.$t('call.callType'),
            name: 'CONNECT_TYPE',
            inputType: 'select',
            data: generateNewKeyValue(
              callType,
              ['code_name', 'code_value'],
              ['label', 'value'],
              this.$t('public.all'),
              true
            )
          },
          {
            label: this.$t('call.RelatedJobList'),
            name: 'IS_BUSINESS_ASSOCIATED',
            inputType: 'select',
            data: [
              { label: this.$t('public.all'), value: '' },
              { label: this.$t('public.yes'), value: 'true' },
              { label: this.$t('public.no'), value: 'false' }
            ]
          },
          {
            label: this.$t('call.fastHangup'),
            name: 'QUICK_HANGUP',
            inputType: 'select',
            data: [
              { label: this.$t('public.all'), value: '' },
              { label: this.$t('call.fastHangUpOption'), value: 'true' },
              { label: this.$t('call.noFastHangUpOption'), value: 'false' }
            ]
          },
          {
            label: this.$t('public.note'),
            name: 'CALL_MEMO',
            inputType: 'input',
          },
          {label: this.$t('call.transferBeforeSeat'), name: 'REF_DISPOSAL_AGENT', inputType: 'owner'},
        ]
        this.formItemsConfigs = config || {}
        this.loading = false
      }
    )
    this.invokMethod()
  },
  mounted() {
    if(this.shortcutOpen) {
      document.addEventListener('keydown', this.shortcutDispatch)
    }
  },
  beforeDestroy() {
    document.removeEventListener('keydown', this.shortcutDispatch)
  }
}
function generateNewKeyValue(list, oldKeys, newKeys, label, flag, currentType) {
  // 数据类型转换
  let result = []
  if (
    !Array.isArray(list) ||
    !Array.isArray(oldKeys) ||
    !Array.isArray(newKeys) ||
    oldKeys.length !== newKeys.length
  ) {
    return result
  }
  if (Array.isArray(label)) {
    result = deepClone(label)
  } else if (label) {
    result = [{label: label, value: ''}]
  }
  for (let i = 0; i < list.length; i++) {
    let item = {}
    if (flag) {
      list[i].code_name = m7Language('globalChineseKey.' + list[i].code_name, null, true) || list[i].code_name
    }
    for (let j = 0; j < oldKeys.length; j++) {
      let oldKey = oldKeys[j]
      let newKey = newKeys[j]
      // 递归处理多级数据
      if (Array.isArray(list[i][oldKey])) {
        if (list[i][oldKey].length > 0) {
          item[newKey] = generateNewKeyValue(
            list[i][oldKey],
            ['name', 'value'],
            ['label', 'value']
          )
        }
      } else {
        item[newKey] = list[i][oldKey]
      }
    }
    result.push(item)
  }
  return result
}
</script>
<style lang='stylus' scoped>
@import '../../../assets/common.styl';

.adv__wapper {
  width: 60px;
  font-size: 12px;
  line-height: 30px;
  margin-right: 10px;
  flex: 3;
}

.icon-weijielaidianguanli {
  color: $c-main;
}
</style>
